package com.qf.ability.message.handler;

import com.alibaba.fastjson.JSON;
import com.qf.ability.message.entity.Message;
import com.qf.ability.message.entity.Room;
import com.qf.ability.message.entity.UserSession;
import com.qf.ability.message.handler.base.BaseInChannelHandler;
import com.qf.ability.message.utils.RoomUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.kurento.client.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 直播方的提案处理Channel
 * author Ken
 * create_time 2022/10/17
 */
@Component
@ChannelHandler.Sharable
@Slf4j
public class MasterOfferMsgInChannelHandler extends BaseInChannelHandler<Message> {

    @Autowired
    private KurentoClient client;

    @Override
    protected boolean isSupport(Message msg) {
        return msg.getId().equals("masterOffer");
    }

    @Override
    protected void hander(ChannelHandlerContext ctx, Message msg) {
        //获得课程号
        Integer cid = msg.getCid();
        //获取房间
        Room room = RoomUtils.get(cid);
        //获得媒体轨道
        MediaPipeline mediaPipeline = room.getMediaPipeline();
        //创建当前媒体端的WebRtcEndPoint
        WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(mediaPipeline).build();
        //设置到直播用户中
        room.getMaster().setWebRtcEndpoint(webRtcEndpoint);

        //给当前端点设置Ice候选者发现监听
        webRtcEndpoint.addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() {
            @Override
            public void onEvent(IceCandidateFoundEvent iceCandidateFoundEvent) {
                Message resultMsg = new Message()
                        .setId("iceCandidate")
                        .setContent(JSON.toJSONString(iceCandidateFoundEvent.getCandidate()));

                //发送给客户端
                ctx.channel().writeAndFlush(resultMsg);
            }
        });

        //连接状态改变事件
        webRtcEndpoint.addConnectionStateChangedListener(new EventListener<ConnectionStateChangedEvent>() {
            @Override
            public void onEvent(ConnectionStateChangedEvent event) {
                log.debug("[conn] 服务器连接状态 - {}", event.getNewState());
                if (event.getNewState() == ConnectionState.CONNECTED) {
                    //服务器连接成功
                    room.setPlayer(true);
                    //通知所有连接的Slave
                    for (UserSession slave : room.getSlaves().values()) {
                        slave.getChannel().writeAndFlush(new Message().setId("masterOnline"));
                    }
                }
            }
        });

        //端点接收提案，并且返回应答
        String sdpAnswer = webRtcEndpoint.processOffer((String) msg.getContent());
        //将应答发给客户端
        Message resultMsg = new Message()
                .setId("answerResult")
                .setContent(sdpAnswer);
        ctx.channel().writeAndFlush(resultMsg);

        //开始发现ICE候选者
        webRtcEndpoint.gatherCandidates();
    }
}
